// Copyright (c) 2025, qiushike and contributors
// For license information, please see license.txt

frappe.ui.form.on("Job Card Scan Input", {
	setup(frm){
		frm.set_query("work_order", function () {
			return {
				filters: [
					["Work Order", "docstatus", "=", 1],
					["Work Order", "status", "in", ["Not Started", "In Process"]]
				],
			};
		});
		//设置为该工单下个工序
		// frm.set_query("operation", function () {
		// 	return {
			
		// 	};
		// });
		frm.set_query("defect_code", "tracking_details", function (doc, cdt, cdn) {			
			return {
				query: "light_mes.light_mes.doctype.job_card_scan_input.job_card_scan_input.defect_code_query",
				filters: {
					operation: frm.doc.operation,
				},
			};		
		})
		frm.set_query("employee", function () {			
			return {
				query: "light_mes.light_mes.doctype.job_card_scan_input.job_card_scan_input.employee_query",
				filters: {
					operation: frm.doc.operation,
				},
			};		
		})
		frm.set_query("tracking_number", "tracking_details", function (doc, cdt, cdn) {			
			return {
				filters: {
					work_order: frm.doc.work_order,
				},
			};		
		})
	},

	onload(frm){
		// 设置员工，工序，工站默认值，如果仅有一个值，隐藏字段
		[
			["Employee", "employee"],
		 	["Operation", "operation"],
			["Workstation", "workstation"]
		].forEach(r => set_field_default_value(frm, r[0], r[1]));
		// 是否不是生成追踪号的工序，直接隐藏工单号字段，即只支持扫追踪号模式
	},

	work_order(frm){
		frm.clear_table("tracking_details");
		frm.call({
			method: "get_work_order_next_operations",
			doc: frm.doc,
			callback: function (r) {
				const operations = r.message;
				if (operations) {
					["operation", "dynamic_fields", "job_card", "for_quantity"].forEach(field => refresh_field(field));										
					if (operations.length === 1) {
						frm.set_df_property("operation", "read_only", 1);
					} else {
						// 设置下拉框可开始的下道（并行）工序
						frm.set_query("operation", function () {
							return {
								filters: {
									name: ["in", operations],
								},
							};
						});
					}
				}
				frm.trigger('show_dynamic_fields');
			},
		});
	},

	// 设置员工组
	workstation(frm){
		frappe.model.with_doc("Workstation", frm.doc.workstation)
		.then((r) => {
			if (r && r.job_card_by_employees){
				frappe.model.clear_table(frm.doc, "employees");
				frappe.run_serially([
					// 要先获取链接字段标题
					() => {
						r.employees.forEach((d) => {
							frappe.utils.fetch_link_title("Employee", d.employee);
						})    
					},
					() => {
						r.employees.forEach((d) => {
							let row = frappe.model.add_child(frm.doc, "Assigned Employee", "employees");
							frappe.model.set_value(row.doctype, row.name, "employee", d.employee);							                              
						});
						frm.set_df_property("employees","hidden", 0);
						refresh_field("employees");						
					},                        
				]);            						
			}
		})
	},

	show_dynamic_fields(frm){
		// 根据tracking type动态显示创建与打印追踪号按钮
		const doc = frm.doc
		if (doc.tracking_type && !doc.tracking_type.includes('New Tracking Number')){
			frm.set_df_property("work_order", "hidden", 1);	
		}
		if (
			doc.tracking_type && (doc.tracking_type.includes('New Tracking Number') || 
			doc.tracking_details.length && doc.tracking_type.includes('New Combined Tracking Number'))
		) {
			frm.set_df_property("create_tracking_numbers", "hidden", 0);
			//frm.set_df_property('create_tracking_numbers', 'cssClass', 'btn-primary');
			$(frm.fields_dict['create_tracking_numbers'].$input).addClass('btn-primary');
        	frm.refresh_fields('create_tracking_numbers');
			if (doc.tracking_type && doc.tracking_type.includes('New Tracking Number')){
				frm.set_df_property("tracking_number", "hidden", 1);
			}			
		}
		if (doc.tracking_type && doc.tracking_details.length){
			frm.set_df_property("print_tracking_numbers", "hidden", 0);			
		}
		if (
			doc.tracking_type && (doc.tracking_type.includes('New Tracking Number') || 
			doc.tracking_details.length && doc.tracking_type.includes('New Combined Tracking Number'))
		){
			hide_grid_columns(frm, ["combine_id"], "tracking_details", 0)
		}
	},

    refresh: function (frm) {
		frm.disable_save();
		frm.trigger('show_dynamic_fields');
		frm.page.set_primary_action(__("Update Job Card"), () => {
			let btn_primary = frm.page.btn_primary.get(0);
			let freeze_message;
			freeze_message = __("Updating Job Card ...");
			
			return frm.call({
				doc: frm.doc,
				btn: $(btn_primary),
				method: "update_job_card",
				freeze: 1,
				freeze_message: freeze_message,
				callback: function (r) {
					frm.reload_doc();
					frappe.show_alert(__("Updated Job Card OK"));
				}	
			});
		});
    },

	fetch_tracking_numbers(frm) {
        if (frm.doc.work_order && frm.doc.operation){
            show_fetch_tracking_numbers_dialog(frm);
        }
	},

    tracking_number: function (frm) {
		if (frm.doc.tracking_number && frm.doc.tracking_number.length>4){
			let details = frm.doc.tracking_details;
			let tracking_field = frm.get_field("tracking_number");
			if (details.length && details.filter(
					r => r.tracking_number===frm.doc.tracking_number ||
						 r.parent_tracking_number===frm.doc.tracking_number
				).length>0
			){
				tracking_field.set_description(__("Duplicate Scan"));
				frm.set_value("tracking_number", "");
			} else {
				frm.call({
					method: "get_tracking_number",
					doc: frm.doc,
					callback: function (r) {
						refresh_field("tracking_details");
						frm.set_value("tracking_number", "");
						let msg;
						if (r.exc){
							msg = __("Scanned failed");
						} else if (!r.message) {
							msg = __("Scanned OK");
						} else {
							msg = r.message;
						}
						tracking_field.set_description(msg);
						frm.trigger('show_dynamic_fields');
					},
				});
			}						
		}
	},

	create_tracking_numbers: function(frm){
		if (frm.doc.tracking_type == "New Tracking Number") {
			frappe.prompt(
				{
					fieldtype: "Int",
					label: __("Quantity"),
					fieldname: "qty",
					default: 6,
				},
				(data) => {
					frappe.call({
						method: "light_mes.api.generate_tracking_numbers",
						args: {
							work_order: frm.doc.work_order,
							count: data.qty
						},
						callback: function (r) {
							tracking_number_list = r.message;
							if (tracking_number_list && tracking_number_list.length) {
								for (let tracking_number of tracking_number_list) {
									let child = frm.add_child("tracking_details");
									child.tracking_number = tracking_number;
								}
								frm.set_value('rolls', tracking_number_list.length);
								frm.refresh_fields();
								//refresh_field("tracking_details");
								frappe.show_alert(__("Created tracking numbers OK"));
							}
						},
					});
				},
				__("Enter Value")
			);			
		} else if (frm.doc.tracking_type == "New Combined Tracking Number")  {
			frappe.call({
				method: "light_mes.api.generate_combined_tracking_numbers",
				args: {
					work_order: frm.doc.work_order,
					tracking_details: frm.doc.tracking_details
				},
				callback: function (r) {
					details = r.message;
					if (details && details.length) {
						// 刷新parent tracking number字段
						for (let row of frm.doc.tracking_details){							
							let matched_row = details.filter(r => r.tracking_number===row.tracking_number)
							if (matched_row) row.parent_tracking_number = matched_row[0].parent_tracking_number
						}
						refresh_field("tracking_details");
						frappe.show_alert(__("Created combined tracking numbers OK"));
					}
				},
			});
		}
    },

	print_tracking_numbers: function(frm){
		// 根据工序不同，需打印分条卷或拼卷标签
		let names = frm.doc.tracking_details.map(r=>r.tracking_number)
		if (frm.doc.tracking_type && frm.doc.tracking_type.includes('New Combined Tracking Number')){
			names = frm.doc.tracking_details.map(r=>r.parent_tracking_number);
			let unique_names = [];
			let seen = new Set(); // 使用 Set 来高效跟踪已存在的名称
			
			for (let name of names) {
			  if (!seen.has(name)) { // 检查名称是否已存在于 Set 中
				unique_names.push(name);
				seen.add(name); // 将新名称添加到 Set 中
			  }
			}
			names = unique_names;
		} 
		const doctype = "Tracking Number";
		names=JSON.stringify(names);
		const print_format = "追踪号标签";
		const pdf_options = JSON.stringify({
			"page-height": "82mm",
			"page-width": "60mm",
		});
		const w = window.open(
			"/api/method/frappe.utils.print_format.download_multi_pdf?" +
				"doctype=" +
				encodeURIComponent(doctype) +
				"&name=" +
				encodeURIComponent(names) +
				"&format=" +
				encodeURIComponent(print_format) +
				"&no_letterhead=1" +
				//(with_letterhead ? "0" : "1") +
				"&letterhead=" +
				encodeURIComponent("") +
				"&options=" +
				encodeURIComponent(pdf_options)
		);

		if (!w) {
			frappe.msgprint(__("Please enable pop-ups"));
		}
	},

	operation: function(frm){
		frappe.db.get_value("Operation", frm.doc.operation,
			"tracking_type",
			(r) => {frm.set_value("tracking_type", r.tracking_type)}
		);
	},

	rolls: function(frm){
		if (frm.doc.rolls && frm.doc.conversion_factor){
			frm.set_value("completed_qty", frm.doc.rolls * frm.doc.conversion_factor);
		}
	}
});

frappe.ui.form.on("Tracking Detail", {
	tracking_number(frm){
		frm.set_value('rolls', frm.doc.tracking_details.length);
		frm.set_value('completed_qty') = frm.doc.rolls * frm.doc.conversion_factor;
	}
})

// 自定义对话框函数
function show_fetch_tracking_numbers_dialog(frm) {	
	// 创建对话框
	const d = new frappe.ui.Dialog({
		title: __("Select Tracking Numbers"),
		fields: [
			{
				fieldtype: 'HTML',
				fieldname: 'results_area'
			}
		],
		primary_action_label: __('Add Tracking Numbers'),
		primary_action: function() {
			// 获取选中的项目
			const selected_items = [];
			d.$wrapper.find('input[type=checkbox]:checked').each(function() {
				if ($(this).attr('id') !== 'select-all') {
					const item = JSON.parse($(this).attr('data-item'));
					selected_items.push(item);
				}
			});
			
			if (selected_items.length === 0) {
				frappe.msgprint(__('Please select at least one item'));
				return;
			}
			
			// 添加项目到表单 - 传递对话框对象
			add_items_to_form(frm, selected_items, d);
			
			// 关闭对话框
			d.hide();
		}
	});
	
	// 设置对话框宽度
	//d.$wrapper.find('.modal-dialog').css('max-width', '90%');
	//d.$wrapper.find('.modal-dialog').css('width', '500px');
	
	// 显示对话框
	d.show();
	
	// 初始搜索
	search_items();
	
	// 添加延迟搜索功能
	let search_timeout = null;
	d.$wrapper.find('input[data-fieldname="search"]').on('input', function() {
		clearTimeout(search_timeout);
		search_timeout = setTimeout(function() {
			search_items();
		}, 300);
	});
	
	// 搜索函数
	function search_items() {		
		// 执行查询
		frappe.call({
			method: 'light_mes.light_mes.doctype.job_card_scan_input.job_card_scan_input.get_tracking_numbers',
			args: {
				work_order: frm.doc.work_order,
				operation: frm.doc.operation,				
			},
			callback: function(r) {
				if (r.message && r.message.length > 0) {
					// 构建表格HTML 宽度要减少
					let html = `
					<div style="max-height: 200px; overflow-y: auto; margin-top: 15px;">
						<table class="table table-bordered table-hover" style="cursor: pointer; width: 100%;">
							<thead>
								<tr class="active">
									<th style="width: 5px; text-align: center;">
										<input type="checkbox" id="select-all">
									</th>
									<th style="width: 80%; text-align: left; vertical-align: middle;">${__('Tracking Number')}</th>									
								</tr>
							</thead>
							<tbody>
					`;
					
					let filtered_items = r.message;				
					filtered_items.forEach(function(item) {
						const item_json = JSON.stringify(item);
						html += `
							<tr>
								<td style="text-align: center;"><input type="checkbox" data-item='${item_json}'></td>
								<td style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left;">${item.tracking_number || ''}</td>								
							</tr>
						`;
					});
					
					html += `
							</tbody>
						</table>
					</div>
					`;
					
					d.fields_dict.results_area.$wrapper.html(html);
					
					// 添加全选功能
					d.$wrapper.find('#select-all').on('click', function() {
						const checked = $(this).prop('checked');
						d.$wrapper.find('input[type=checkbox]').prop('checked', checked);
					});
					
					// 添加行点击选择功能
					d.$wrapper.find('tbody tr').on('click', function(e) {
						if (e.target.type !== 'checkbox') {
							const checkbox = $(this).find('input[type=checkbox]');
							checkbox.prop('checked', !checkbox.prop('checked'));
						}
					});
					
					// 添加鼠标悬停显示完整内容的功能
					d.$wrapper.find('td[style*="overflow: hidden"]').each(function() {
						$(this).attr('title', $(this).text());
					});
				} else {
					d.fields_dict.results_area.$wrapper.html(`
						<div class="text-center" style="margin-top: 20px;">
							<p>${__('No items found')}</p>
						</div>
					`);
                    d.hide();
				}
			}
		});
	}
}

// 添加到表单子表
function add_items_to_form(frm, selected_items, dialog) {
	// 清空现有行
    const child_field = 'tracking_details';
	frm.clear_table(child_field);
	
	// 添加选中行
	selected_items.forEach(function(item) {
		const child = frm.add_child(child_field);		
		// 设置基本字段
		child.tracking_number = item.tracking_number;		
	});
	
	// 刷新表格
	frm.refresh_field(child_field);
}

function hide_grid_columns(frm, fields, table_field, hidden) {
	let grid = frm.get_field(table_field).grid;
	let changed = false

	for (let field of fields) {
		if (grid.fields_map[field].hidden !== hidden){
			grid.fields_map[field].hidden = hidden;
			changed = true;
		}
		//grid.fields_map[field].in_list_view = 0;
	}
	if (!changed){
		return
	}
	
	grid.visible_columns = undefined;
	frappe.model.user_settings.remove(grid.frm.doctype, 'GridView');
	grid.setup_visible_columns();
	
	grid.header_row.wrapper.remove();
	delete grid.header_row;
	grid.make_head();
	grid.reset_grid();
}

function set_field_default_value(frm, doctype, field){
	frappe.call({
		method: "frappe.client.get_list",
		args: {doctype: doctype},
		callback: function(r){
			let values = r.message;
			if (values && values.length===1){
				frm.set_value(field, values[0].name);
				if (field=="operation"){
					frappe.db.get_value("Operation", frm.doc.operation,
						"tracking_type",
						(res) => {frm.set_value("tracking_type", res.tracking_type)}
					);
				}
				frm.set_df_property(field, "hidden", 1);
				refresh_field(field);
			}
		}
	})
}